import Joi from "joi";
import { getDB } from "~/server/utils/db/mysql";
import { getLoginUid, responseJson } from "~/server/utils/helper";
import path from "path";
import * as fs from "fs";

export default defineEventHandler(async (event) => {
  //判断用户登录
  let uid = getLoginUid(event);
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请先登录", {});
  }
  //获取数据
  const body = await readMultipartFormData(event);

  if (body) {
    if (
      body[0].type !== "image/jpeg" &&
      body[0].type !== "image/png" &&
      body[0].type !== "image/jpg"
    ) {
      return responseJson(1, "请上传jpg/png/jpeg类型的图片", {});
    }
    //图片名称
    const fileName = Date.now() + "-" + body[0].filename;
    //图片路径
    const filePath = path.join("./public", "img", fileName);
    //图片数据
    const buffer = body[0].data;

    fs.writeFile(filePath, buffer, (err) => {
      if (err) {
        console.error("保存图片文件失败:", err);
      }
    });

    //存储图片路径
    const avatarUrl = "/img/" + fileName;

    const con = getDB();
    try {
      //插入users
      const [result] = await con.execute(
        "UPDATE `users` SET `avatar`=? WHERE `id`=?",
        [avatarUrl, uid]
      );
      // @ts-ignore
      if (result.affectedRows === 0) {
        return responseJson(1, "上传头像失败~", {});
      }
      return responseJson(0, "ok~", {
        avatar: avatarUrl,
      });
    } catch (e) {
      console.error("上传头像失败:", e);
      // @ts-ignore
      setResponseStatus(event, 500);
      return responseJson(1, "服务器错误", {});
    }
    // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
    // 连接池会自动管理连接的获取和释放
  }

  return responseJson(1, "请上传头像~", {});
});
